package com.lance.answer.question_answer.xj_new;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.Item;
import com.lance.answer.dto.QuestionDetailNew;
import com.lance.answer.dto.TestExam;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;

/**
 * 2021-10-26 直接解析某个课程的JSON
 */
public class BatchParseJson {


    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.cssSelector(cssSelector))));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> d.findElement(By.cssSelector(cssSelector))));
    }

    public static void main(String[] args) throws Exception {



        WebDriver driver = Util.getDriver(null);
        String url = "https://xjskk.open.com.cn/teacherspace-auth/#/login";
        // 打开指定的网站
        driver.get(url);
        Thread.sleep(200);

        for (WebElement we : driver.findElements(By.className("el-input__inner"))) {
            if ("text".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
            if ("password".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
        }
        driver.findElement(By.cssSelector("button[class='el-button login-ruleForm-btn el-button--primary']")).click();

        // 进入课程观察员角色的页面

        findElementByCssSelector(driver, "div[title='课程观察员']", 20).click();

        Thread.sleep(5000);


        Set<Cookie> cookies = driver.manage().getCookies();
        String studentSpaceProfile = Util.getStudentSpaceProfile(cookies);
        String authorization = Util.getAuthorization(cookies);
        // 初始化头部
        Map<String, String> heads = XinJiangUtil.initHttpHeads(studentSpaceProfile, authorization);

        String cookie = Util.getCookie(cookies);

        driver.navigate().refresh();
        Thread.sleep(4000);
        cookies = driver.manage().getCookies();
        // 初始化头部
        cookie = Util.getCookie(cookies);




        Map<Integer,String> cMap = Maps.newHashMap();


        List<String> ids = Lists.newArrayList();
        for(File f1:new File("D:\\新疆一体化平时作业").listFiles()){
            ids.add(f1.getName());
        }

        InputStream inputStream = new FileInputStream("E:\\排名map.txt");
        List<String> allKeyValues = IOUtils.readLines(inputStream, "utf-8");

        Map<String,String> mapTmp = Maps.newHashMap();
        for(String keyValues:allKeyValues){
            String[] strs = keyValues.split("&");
            String k1 = strs[0];
            String v1 = strs[1];
            mapTmp.put(k1,v1);
        }

        for(File file:new File("E:\\XjStudentCourseInfoTmp\\names").listFiles()){
            String fileName = file.getName();
            String code =  fileName.substring(0,fileName.length()-5);
            if(!ids.contains(code)){
                cMap.put(Integer.parseInt(code),mapTmp.get(code));
            }
            System.err.println("code:"+code);
            System.err.println("mapTmp.get(code):"+mapTmp.get(code));
        }

        // LINSHI FIXME 4-11
        // LINSHI
    //    cMap.clear();
//        cMap.put(34139,"实用写作");
//        cMap.put(37526,"语言学概论（本）");
//        cMap.put(33956,"言语交际");
//        cMap.put(33965,"职业生涯规划（1）");
//        cMap.put(37542,"简明新疆地方史教程");
//        cMap.put(39132,"心理健康");
//        cMap.put(33960,"企业文化");
//        cMap.put(38510,"人才测评技术及应用");
//        cMap.put(38557,"劳务派遣讲座");
//        cMap.put(38539,"劳动争议与仲裁讲座");
//        cMap.put(39068,"人文社会科学基础(A)");
//        cMap.put(38933,"文艺理论基础");
//        cMap.put(39056,"现代教师学导论");
//        cMap.put(39008,"小学儿童教育心理学");
//        cMap.put(38652,"心理学");
//        cMap.put(39104,"阅读与写作(2) ");
        // LINSHI FIXME
        // LINSHI
        cMap.clear();
        cMap.put(42276,"人文社会科学基础");
        for(int openCourseId:cMap.keySet()){

            String subjectName = cMap.get(openCourseId);
            Map<String,Object> map = Maps.newHashMap();
            map.put("pageNumber",1);
            map.put("pageSize",20);
            map.put("openCourseId",openCourseId);
            map.put("name","");
            map.put("type",3);
            StringBuilder sb = new StringBuilder("https://xjskk.open.com.cn/api/teacher/teacher-space-service/testExam/getTestExamList?");
            for(Map.Entry<String,Object> entry:map.entrySet()){
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            String getUrl1 = sb.toString();
            getUrl1 = getUrl1.substring(0,getUrl1.length()-1);

            String getTestExamList = HttpUtil.get(getUrl1, cookie, heads);

            TestExam testExam = JSON.parseObject(getTestExamList,TestExam.class);
            System.err.println("getTestExamList:"+getTestExamList);

            List<String> idList = Lists.newLinkedList();
            for(TestExam.ContentDTO.ItemsDTO itemsDTO:testExam.getContent().getItems()){
                // fixme 2022-5-15 这个改成了数组？？？？？？？
              //  idList.add(itemsDTO.getPaperUidArray());
                System.err.println("itemsDTO.getPaperUidArray():"+itemsDTO.getPaperUidArray());
                String paperArrayString = itemsDTO.getPaperUidArray();
                String[] paperArray = paperArrayString.split(",");
                idList.addAll(new ArrayList<>(Arrays.asList(paperArray)));
            }

            List<String> papers = Lists.newLinkedList();
            for(String paperId:idList){
                String getUrl2 = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/testPaper/getPaperById?testPaperId="+paperId;
                System.err.println("paperId:"+paperId);
                System.err.println("HttpUtil.get(getUrl2, cookie, heads):"+HttpUtil.get(getUrl2, cookie, heads));
                papers.add(HttpUtil.get(getUrl2, cookie, heads));
            }

            save(papers,openCourseId,subjectName);

            Thread.sleep(10000);

        }



        System.err.println("end........");


    }

    public static void save( List<String> papers,int openCourseId,String subjectName)throws Exception{



        List<Question> questions = Lists.newArrayList();
        for (String json:papers){

            if(Strings.isNullOrEmpty(json)){
                continue;
            }

            QuestionDetailNew questionDetail = JSONObject.parseObject(json, QuestionDetailNew.class);

            QuestionDetailNew.ContentDTO contentDTO= questionDetail.getContent();
            System.err.println("contentDTO:"+contentDTO);

            if(null == contentDTO.getItems()){
                System.err.println("??????:"+questionDetail);
                continue;
            }
            for (QuestionDetailNew.ContentDTO.ItemsDTO itemsDTO:contentDTO.getItems()) {
                Question question = new Question();
                question.setTitle(itemsDTO.getI2());
//                        if(null!=contentDTO.getI9() ){
//                            question.setScore(contentDTO.getI9() + 0.0);
//                        }
                question.setScore(itemsDTO.getI9());
                int i3 = itemsDTO.getI3()==null?888:itemsDTO.getI3();
                question.setQuestionType(i3);


                if (i3 <= 3) {
                    if (i3 == 1) {
                        question.setQuestionTypeDesc("单选题");
                    } else if (i3 == 2) {
                        question.setQuestionTypeDesc("多选题");
                    } else {
                        question.setQuestionTypeDesc("判断题");
                    }


                    List<Item> items = Lists.newArrayList();
                    question.setItems(items);
                    List<String> answers = itemsDTO.getI6();
                    for (String answer : answers) {
                        Item item = new Item(answer, "");
                        items.add(item);
                    }

                    // 正确的答案所在的位置
                    List<String> correctIndex = itemsDTO.getI7();
                    List<String> correctList = Lists.newArrayList();
                    for (String cIndex : correctIndex) {
                        int index = Integer.parseInt(cIndex);
                        if (i3 != 3) {
                            correctList.add(answers.get(index));
                        } else {

                            System.err.println("???????????????:"+JSON.toJSONString(answers)+"\t correctIndex"+JSON.toJSONString(correctIndex));

                            if (correctIndex.get(0).equals("0")) {
                                correctList.add("对");
                            }else if (correctIndex.get(0).equals("1")) {
                                correctList.add("错");
                            }
//                            else {
//                                correctList.add("对");
//                            }
                        }
                    }
                    String[] correctArray = new String[]{};
                    correctArray = correctList.toArray(correctArray);
                    System.err.println("correctArray:" + JSON.toJSONString(correctArray));
                    question.setCorrectArray(correctArray);

                    System.err.println("????????????111:" + JSON.toJSONString(question.getCorrectArray()));
                } else {
                    if (i3 == 4) {
                        question.setQuestionTypeDesc("填空题");
                    }else if(i3 == 5) {
                        question.setQuestionTypeDesc("阅读理解");
                    }
                    else {
                        question.setQuestionTypeDesc("简答题");
                    }
                    // 正确的答案所在的位置
                    List<String> answers2 = itemsDTO.getI6();
                    // FIXME 去掉/n \n
                    List<String> answers = Lists.newArrayList();
                    for(String s:answers2){
                        answers.add(s.replaceAll("\n",""));
                    }
                    if(i3==5){
                        System.err.println("答案："+JSON.toJSONString(itemsDTO));
                        answers.clear();
                        for(QuestionDetailNew.ContentDTO.ItemsDTO.SubDTO subDTO:itemsDTO.getSub()){
                            /**
                             * "Choices":[
                             * {
                             * "IsCorrect":true,
                             * "I1":"A",
                             * "I2":"CO是主要污染物"
                             * },
                             */
                            for(QuestionDetailNew.ContentDTO.ItemsDTO.SubDTO.ChoicesDTO choicesDTO:subDTO.getChoices()){
                                if(choicesDTO.getIsCorrect()){
                                    answers.add(choicesDTO.getI2());
                                    System.err.println("choicesDTO.getI2():"+choicesDTO.getI2());
                                    break;
                                }
                            }

                        }
                    }

                    String[] correctArray = new String[]{};
                    correctArray = answers.toArray(correctArray);
                    question.setCorrectArray(correctArray);


                }

                questions.add(question);

                System.err.println("??????????????222:" + JSON.toJSONString(question.getCorrectArray()));
            }
        }


        //   Collections.sort(questions);
        List<Map<String, Object>> answers = new ArrayList<>();
        for (Question question : questions) {
            String title = question.getTitle();
            title = Util.dealContent(title);
            Map<String, Object> answerMap = new HashMap<>();
            answerMap.put("questionType", question.getQuestionType());
            answerMap.put("answerType", "click");
            answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
            System.err.println("DealJsonString.delHTMLTag(title):"+DealJsonString.delHTMLTag(title));
            answerMap.put("questionTitle", DealJsonString.delHTMLTag(title));
            answerMap.put("questionCode", question.getQuestionCode());
            answerMap.put("items", question.getItems());

            answerMap.put("answers", question.getCorrectArray());

            System.err.println("question.getCorrectArray():" + JSON.toJSONString(question.getCorrectArray()));
            answerMap.put("score", question.getScore());
            answers.add(answerMap);
        }

        FileUtils.write(new File("D:\\新疆一体化平时作业\\" + openCourseId + "\\" + subjectName + "（平时作业）.json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");

        Thread.sleep(1000);
    }


}
